# -*- coding: utf-8 -*-

"""
新闻管理函数
"""
from ...pao_python.pao.data import process_db, dataframe_to_list, DataProcess, DataList
import pandas as pd
import uuid
import datetime
import re
import hashlib
from ...pao_python.pao.service.security.security_service import RoleService
from ...pao_python.pao.service.security.security_utility import get_current_account_id
from ...service.common import insert_data, find_data, update_data, delete_data, get_condition, get_info, get_current_user_id, get_user_id_or_false, get_current_role_id
from ...service.buss_pub.bill_manage import BillManageService, OperationType, TypeId, Status
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from ...service.mongo_bill_service import MongoBillFilter
from ...service.buss_mis.service_follow_collection import ServiceFollowCollectionService
from ...service.buss_mis.activity_manage import ActivityManageService, Auditstatus
from ...service.buss_pub.message_manage import MessageManageService, MessageState


class NewsService(MongoService):
    """ 新闻管理 """

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        DataProcess.__init__(self, db_addr, db_port, db_name, db_user, db_pwd)
        # self.db_name = db_name
        self.inital_password = inital_password
        self.session = session
        self.bill_manage_service = BillManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session
        )
        self.ServiceFollowCollectionService = ServiceFollowCollectionService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session
        )
        self.ActivityManageService = ActivityManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session
        )
        self.MessageManageService = MessageManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session
        )

    def get_news_list(self, org_ids, condition, page, count):
        """获取新闻列表

        Arguments:
            condition   {dict}      条件
            page        {number}    页码
            count       {number}    条数
        """
        if 'date_range' in list(condition.keys()):
            condition['start_date'] = condition['date_range'][0]
            condition['end_date'] = condition['date_range'][1]
        keys = ["id", 'title', 'promulgator',
                'start_date', 'end_date', 'status', 'organization_id', 'all']
        values = self.get_value(condition, keys)
        _filter_type = MongoBillFilter()
        _filter_type.match_bill((C('organization_id').inner(org_ids)) & (C("name").like('新闻')) | (C("name").like('news'))).project(
            {"_id": 0})
        res_type = self.query(_filter_type, "PT_Article_Type")
        _filter = MongoBillFilter()
        _filter.lookup_bill("PT_User", "promulgator_id", "id", "promulgator")\
            .lookup_bill('PT_Service_Follow_Collection', 'id', 'business_id', 'likes_info')\
            .add_fields({'likes_count': self.ao.size(self.ao.array_filter(
                "$likes_info", "li", ((F('$li.object') == '养老资讯') & (F('$li.type') == 'likes')).f))})\
            .add_fields({'share_count': self.ao.size(self.ao.array_filter(
                "$likes_info", "li", ((F('$li.object') == '养老资讯') & (F('$li.type') == 'share')).f))})\
            .add_fields({"promulgator": self.ao.array_elemat("$promulgator.name", 0)})\
            .match_bill((C("promulgator").like(values['promulgator']))
                        & (C('title').like(values['title']))
                        & (C("id") == values["id"])
                        & (C("organization_id") == values["organization_id"])
                        & (C("status") == values["status"])
                        & (C('issue_date') >= as_date(values['start_date']))
                        & (C('issue_date') <= as_date(values['end_date'])))

        if 'user_id' in condition:
            # 表示是我发布的
            _filter.match_bill(
                (C('promulgator_id') == get_current_user_id(self.session)))

        if 'all' not in condition:
            # 默认拿已经通过的
            condition_all = 'ts'
        else:
            condition_all = condition['all']
            del(condition['all'])

        if condition_all == 'ts':
            # 只拿审核成功的
            _filter.match_bill(
                (C('step_no') == -1))

        elif condition_all == 'sh':
            # 审核列表只拿待审批的
            role_id = get_current_role_id(self.session)
            _filter.lookup_bill('PT_Approval_Process', 'id', 'business_id', 'process')\
                .add_fields({'new_field': self.ao.array_filter("$process", "aa", ((F('$aa.approval_user_id') == role_id) & (F('$aa.step_no') == (F('step_no'))) & (F('$aa.status') == '待审批')).f)}).match((C("new_field") != None) & (C("new_field") != []))

        # 判断本人是否点赞了
        user_id = get_user_id_or_false(self.session)
        if user_id != False:
            _filter.add_fields({'is_likes': self.ao.size(self.ao.array_filter(
                "$likes_info", "li", ((F('$li.user_id') == user_id) & (F('$li.object') == '养老资讯') & (F('$li.type') == 'likes')).f))})
            _filter.add_fields({'is_share': self.ao.size(self.ao.array_filter(
                "$likes_info", "li", ((F('$li.user_id') == user_id) & (F('$li.object') == '养老资讯') & (F('$li.type') == 'share')).f))})

        if len(res_type) > 0:
            _filter.match_bill((C('type_id') == res_type[0].get('id')))

        _filter.sort({'create_date': -1})\
            .project({
                "_id": 0,
                "promulgator._id": 0,
                "bill_status": 0,
                "GUID": 0,
                "version": 0,
                "likes_info": 0,
                "valid_bill_id": 0,
                "new_field._id": 0,
                "process._id": 0,
            })
        res = self.page_query(_filter, "PT_Article", page, count)
        return res

    def get_news_list_picture(self, condition):
        keys = ["id"]
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('step_no') == -1))\
            .lookup_bill("PT_Article_Type", "type_id", "id", "type")\
            .match_bill(C("type.name").like('新闻') | C("type.name").like('news'))\
            .add_fields({"picture": self.ao.array_elemat("$app_img_list", 0)})\
            .sort({'create_date': -1})\
            .project({"_id": 0, "type._id": 0})
        res = self.page_query(_filter, "PT_Article", 1, 5)
        return res

    def update_news(self, data):
        """# 新增新闻"""
        res = "Fail"

        # 定义审批类型
        define_type = 'newsPublish'
        # 数据表
        ptdb = 'PT_Article'

        # 带有id，编辑状态
        if 'id' in list(data.keys()):

            # 找出数据库里的状态
            _filter_news = MongoBillFilter()
            _filter_news.match_bill((C("id") == data['id'])).project(
                {"_id": 0})
            res_news = self.query(_filter_news, "PT_Article")

            if len(res_news) > 0 and 'step_no' in res_news[0] and res_news[0]['step_no'] == -1:
                # 赋值待审批数据
                # 第一步
                data['step_no'] = 1
                # 待审批状态
                data['status'] = Auditstatus.unaudited.value
                # 已审核状态下的重新编辑
                return self.ActivityManageService.reChange(data, res_news, TypeId.news.value, ptdb, define_type)

            # 进入审批流程
            if 'is_sp' in list(data.keys()):
                
                # 审批流程要判断这个消息提醒是否可以设置已读
                _filter_msg = MongoBillFilter()
                _filter_msg.match_bill((C('business_id') == data['id']) & (C('message_state') == MessageState.Unread.value))\
                    .sort({'create_date': -1})\
                    .project({'_id': 0})
                res_msg = self.query(
                    _filter_msg, "PT_Message")

                if len(res_msg) > 0:
                    # 设置已读
                    self.MessageManageService.set_message_already_read({
                        'id':res_msg[0]['id']
                    })

                # 统一不通过
                if data['sp_status'] == Auditstatus.reject.value:
                    # 进入审批流程
                    # 获取审批数据
                    newData = self.ActivityManageService.getSpRes(data)
                    # 公共审批流程
                    res = self.ActivityManageService.changeSpProcess(newData, TypeId.activity.value,
                                                                     ptdb, define_type, '全部')

                    return res
                if 'step_no' in list(data.keys()):
                    # 步骤1，资料审核
                    if data['step_no'] == 1:
                        # 资料审核，由于不通过都在统一不通过，所以这里肯定是通过的
                        # 进入审批流程
                        # 获取审批数据
                        newData = self.ActivityManageService.getSpRes(data)
                        # 公共审批流程
                        res = self.ActivityManageService.changeSpProcess(newData, TypeId.activity.value,
                                                                         ptdb, define_type, '全部')
                    elif data['step_no'] == 2:
                        # 审核完成，由于不通过都在统一不通过，所以这里肯定是通过的
                        # 进入审批流程
                        # 获取审批数据
                        newData = self.ActivityManageService.getSpRes(data)
                        # 公共审批流程
                        res = self.ActivityManageService.changeSpProcess(newData, TypeId.activity.value,
                                                                         ptdb, define_type, '全部')

            else:
                bill_id = self.bill_manage_service.add_bill(
                    OperationType.update.value, TypeId.activity.value, data, ptdb)
                if bill_id:
                    res = 'Success'
        else:
            # 新增一个待审批
            data['promulgator_id'] = get_current_user_id(self.session)
            # 第一步
            data['step_no'] = 1
            # 待审批状态
            data['status'] = Auditstatus.unaudited.value

            # 初始数据
            data['likes'] = 0
            data['share'] = 0

            # 新闻类型
            _filter_type = MongoBillFilter()
            _filter_type.match_bill((C("name").like('新闻')) | (C("name").like('news'))).project(
                {"_id": 0})
            res_type = self.query(_filter_type, "PT_Article_Type")

            if len(res_type) > 0:
                data['type_id'] = res_type[0].get('id')

            # 用来找回这条数据的
            news_data = get_info(data, self.session)

            # 标识新数据
            news_data['is_create'] = True

            # 接入审批流程
            res = self.ActivityManageService.changeSpProcess(news_data, TypeId.activity.value,
                                                             ptdb, define_type, '全部')

            # 插入一个消息提醒
            self.MessageManageService.add_new_message({
                # 新闻标识
                "business_type": 'article',
                # 业务ID
                "business_id": news_data['id']
            })

        # 审核是不会带活动数据的
        # if res == 'Success' and 'title' in data:
        #     real_account_data = OperationRecordObject(
        #         get_current_user_id(self.session), OperationRecordType.publish_activity, data['id'], data['activity_name'])
        #     self.OperationRecordService.insert_record(
        #         real_account_data.to_dict())
        return res

        # 原来的流程
        # if not news.get("status"):
        #     news["status"] = "auditing"
        # # 直接通过
        # news['status'] = 'audit_success'
        # news["issue_date"] = datetime.datetime.now()
        # _filter = MongoFilter()
        # _filter.match((C("bill_status") == "valid") & ((C("name") == '新闻') | (C("name") == 'news'))).project(
        #     {"_id": 0})
        # res_news = self.query(_filter, "PT_Article_Type")
        # if res_news:
        #     news['type_id'] = res_news[0].get('id')
        # else:
        #     news['type_id'] = ''
        # person_id = get_current_user_id(self.session)
        # news["promulgator_id"] = person_id
        # if "id" in list(news.keys()):
        #     bill_id = self.bill_manage_service.add_bill(
        #         OperationType.update.value, TypeId.news.value, news, "PT_Article"
        #     )
        #     if bill_id:
        #         res = "Success"
        #     # res = 'news is uneditable'
        # else:
        #     bill_id = self.bill_manage_service.add_bill(
        #         OperationType.add.value, TypeId.news.value, news, "PT_Article"
        #     )
        #     if bill_id:
        #         res = "Success"
        # return res

    def delete_news(self, news_ids):
        """删除新闻
        Arguments:
        news_ids   {ids}      数据id
        """
        res = "fail"

        def process_func(db):
            nonlocal res
            ids = []
            if isinstance(news_ids, str):
                ids.append(news_ids)
            else:
                ids = news_ids
            for news_id in ids:
                # 查询被删除的数据信息
                data = find_data(
                    db,
                    "PT_Article",
                    {"id": news_id, "bill_status": Status.bill_valid.value},
                )
                if len(data) > 0:
                    self.bill_manage_service.add_bill(
                        OperationType.delete.value,
                        TypeId.news.value,
                        data[0],
                        "PT_Article",
                    )
            res = "Success"
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def update_ctrl(self, condition):
        """# 点赞分享"""
        res = "Failed"
        keys = ["id", 'type']

        if 'id' not in condition or 'type' not in condition or condition['type'] not in ['share', 'likes']:
            return '非法操作！'

        # 判断是否登录
        user_id = get_user_id_or_false(self.session)

        if user_id == False:
            return '用户未登录！'

        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id') == values['id']))\
            .sort({'create_date': -1})\
            .project({"_id": 0})
        res_article = self.query(_filter, "PT_Article")

        if len(res_article) > 0:

            # 检查不让重复点赞
            _filter = MongoBillFilter()
            _filter.match_bill((C('user_id') == user_id) & (C('object') == '养老资讯') & (C('type') == condition['type']))\
                .sort({'create_date': -1})\
                .project({"_id": 0})
            res_sfc = self.query(_filter, "PT_Service_Follow_Collection")

            # 取消点赞
            if condition['type'] == 'likes' and len(res_sfc) > 0:
                if self.ServiceFollowCollectionService.delete_service_follow_collection(res_sfc[0]['id']) == 'Success':
                    return 'Success'

            # 调用接口
            if self.ServiceFollowCollectionService.update_service_follow_collection(values['id'], condition['type'], '养老资讯') != 'Success':
                if condition['type'] == 'likes':
                    return '点赞失败！'
                elif condition['type'] == 'share':
                    return '分享失败！'

            bill_id = self.bill_manage_service.add_bill(
                OperationType.update.value, TypeId.news.value, res_article[0], "PT_Article"
            )
            if bill_id:
                res = "Success"

        return res
